<?php

namespace app\admin\controller;

use app\admin\model\SystemNotice as SystemNoticeModel;
use app\admin\service\OssService;
use app\admin\validate\BannerValidate;
use app\admin\validate\CommonnValidate;
use app\BaseController;

class Notice extends BaseController
{
    protected $middleware = ['Auth'];

    public function list() {
        $params = $this->request->post(['current', 'size']);
        $validate = new CommonnValidate();
        if (!$validate->scene('list')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new SystemNoticeModel();
        $list = $sql
            ->order('create_at desc')
            ->paginate([
                'list_rows'=> request()->param('size'),
                'page' => request()->param('current'),
            ]);
        return result()->success($list);
    }

    public function addEdit() {
        $params = $this->request->post(['id']);
        if(isset($params['id']) && $params['id']) {
            return $this->edit();
        }
        return $this->add();
    }

    public function add() {
        $params = $this->request->post(['title', 'content']);
        $validate = new BannerValidate();
        if (!$validate->scene('addNotice')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new SystemNoticeModel();
        $sql->save($params);
        return result()->success("添加成功");
    }

    public function edit() {
        $params = $this->request->post(['id', 'title', 'content']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $params['image_id'] = ossPathToId($params['image']);
        $sql = new SystemNoticeModel();
        $info = $sql->find($params['id']);
        $info->save($params);
        return result()->success("修改成功");
    }

    public function dels() {
        $params = $this->request->post(['ids']);
        $validate = new CommonnValidate();
        if (!$validate->scene('dels')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new CommonnValidate();
        $sql->destroy($params['ids']);
        return result()->success("删除成功");
    }
}